/*
 * Using Ajax to change password
 */
if (typeof HCM !== 'object') var HCM = {};

HCM.changeEmail = new (function(el) {
    var $root_el = null;
    var edit_button = null;
    var email_input;
    var value_indicator;

    this.onReady = function(el) {
        $root_el = $(el);
        edit_button = $root_el.find('a.ajaxLink');
        email_input = $root_el.find("input#email");
        value_indicator = $root_el.find('.indicator');

        edit_button.click(function(){
            if (edit_button.html() != 'Submit') {
                email_input.val(value_indicator.text());
                value_indicator.hide();
                email_input.show();
                edit_button.html('Submit');
            } else {
                var email_value = email_input.val();
                if (validate(email_value)) {
                    $root_el.find('p.error').hide();
                    $.post('/change/email', {
                        email: email_value
                    }, changeEmailSuccess, 'text');
                } else {
                    $root_el.find('p.error').show();
                }
            }

            return;
        });
    };

    var validate = function() {
        var email_value = $.trim(email_input.val());
        if (email_value == '' || is_valid_email(email_value)) {
            return false;
        } 
        return true;
    };

    var changeEmailSuccess = function(data) {
        email_input.hide();
        value_indicator.text(data);
        value_indicator.show();
        edit_button.html('Edit');
    };
});

$(function() {
    HCM.changeEmail.onReady($('.profileForm .email').get(0));
});